<template>
  <view>
    <my-goods v-for="item in goodsList" :key="item.goods_id" :goods="item">
    </my-goods>
  </view>
</template>

<script>
import myGoods from "../../components/my-goods/my-goods.vue";

export default {
  components: { myGoods },
  data() {
    return {
      queryObj: {
        query: "", // 关键字
        cid: "", // 分类id
        pagenum: 1, // 页码
        pagesize: 10, // 页容量
      },
      goodsList: [], // 搜索到的商品数据数组
      total: 0, //总条数
      isLoadingMore: false, // 是否正在上拉加载
    };
  },
  onLoad(options) {
    this.queryObj.query = options.query || "";
    this.queryObj.cid = options.cid || "";
    // 发请求获取数据
    this.getGoodsListData();
  },
  // 上拉刷新
  onReachBottom() {
    // 正在上拉则 return
    if (this.isLoadingMore) return;

    if (this.goodsList.length >= this.total) {
      uni.showToast({
        title: "没有数据啦~",
        icon: "none",
      });
      return;
    }
    // 继续加载下一页数据
    this.queryObj.pagenum++;
    this.getGoodsListData();
  },
  // 下拉刷新
  onPullDownRefresh() {
    // 把数据清空
    this.queryObj.pagenum = 1;
    this.goodsList = [];
    this.total = 0;
    // 重新加载数据
    this.getGoodsListData(true);
    uni.showToast({
      title: "刷新成功~",
      icon: "none",
    });
  },
  methods: {
    // 发请求获取数据
    async getGoodsListData(isPullDown = false) {
      this.isLoadingMore = true;
      const res = await uni.$request({
        url: "goods/search",
        data: this.queryObj,
        isPullDown,
      });
      // console.log(res);
      if (res.meta.status == 200) {
        this.goodsList = [...this.goodsList, ...res.message.goods];
        this.total = res.message.total;
        this.isLoadingMore = false;
        if (isPullDown) {
          uni.stopPullDownRefresh();
        }
      }
    },
  },
};
</script>

<style></style>
